package cn.edu.tsinghua.weibo.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.tsinghua.weibo.entity.User;
import cn.edu.tsinghua.weibo.util.DB;

@SuppressWarnings("serial")
public class Delete extends HttpServlet {

	private final static String SQL_SEARCH = "select userid from weibo where id=?";
	private final static String SQL_DELETE_WEIBO = "delete from weibo where id=?";
	private final static String SQL_DELETE_COMMENT = "delete from comment where weiboid=?";

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int weiboid = Integer.parseInt(request.getParameter("weiboid"));
		
		try {
			Connection connection = DB.getConnection();
			PreparedStatement preparedStatement = connection.prepareStatement(SQL_SEARCH);
			preparedStatement.setInt(1, weiboid);
			ResultSet resultSet = preparedStatement.executeQuery();
			resultSet.next();
			int userid = resultSet.getInt("userid");
			
			HttpSession session = request.getSession();
			if(userid == ((User)session.getAttribute("user")).getId()) {//当前微博是本人发表的，可以删除
				//先删除所有的评论
				preparedStatement = connection.prepareStatement(SQL_DELETE_COMMENT);
				preparedStatement.setInt(1, weiboid);
				preparedStatement.executeUpdate();
				//再删除当前微博
				preparedStatement = connection.prepareStatement(SQL_DELETE_WEIBO);
				preparedStatement.setInt(1, weiboid);
				preparedStatement.executeUpdate();
			}
			DB.close(resultSet, preparedStatement, connection);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
